package com.freight.message.utils;

import com.alibaba.fastjson.JSON;
import com.freight.common.core.constant.WebsocketConstants;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.simp.SimpMessageSendingOperations;
import org.springframework.messaging.simp.user.SimpUser;
import org.springframework.messaging.simp.user.SimpUserRegistry;
import org.springframework.stereotype.Component;

/**
 * websocket
 */
@Component
public class WebSocketService {

    @Autowired
    private SimpMessageSendingOperations simpMessageSendingOperations;

    @Autowired
    private SimpUserRegistry simpUserRegistry;

    /**
     * 服务端推送消息（广播）
     * 客户端 订阅地址为 /topic/?
     */
    public void sendMessage(String destination, String message) {
        try {
            simpMessageSendingOperations.convertAndSend(WebsocketConstants.SUBSCRIBE_PRE_TOPIC + destination, message);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 服务端推送消息（一对一）
     * 客户端 订阅地址为 /user/{username}/?
     * @param destination
     * @param username
     * @param message
     */
    public void sendMessage(String destination, String username, String message) {
        try {
            // 根据用户名查询当前节点在线用户
            SimpUser simpUser = simpUserRegistry.getUser(username);
            if (simpUser != null) {
                simpMessageSendingOperations.convertAndSendToUser(username, destination, message);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}
